from celery.result import AsyncResult
from flask import Blueprint, jsonify, request, render_template
from sqlalchemy import desc

from applications.common.curd import model_to_dicts
from applications.common.tasks.spider_tasks import crawl_xueqiu_index_eva
from applications.common.utils.http import table_api
from applications.models import FundIndexEva
from applications.schemas import FundIndexEvaSchema

index_eva_bp = Blueprint('indexEva', __name__, url_prefix='/indexEva')


@index_eva_bp.get('/startIndexEvaTask')
def start_index_eva_task():
    task = crawl_xueqiu_index_eva.delay()
    task_result = AsyncResult(task.id)
    result = {
        "task_id": task.id,
        "task_status": task_result.status,
        "task_result": task_result.result
    }
    return jsonify(result)


@index_eva_bp.get('/')
def main():
    create_dates_query = FundIndexEva.query.with_entities(FundIndexEva.create_date).distinct() \
        .order_by(desc('create_date')).all()
    create_dates = [create_date[0] for create_date in create_dates_query]
    return render_template('fund/index_eva/main.html', create_dates=create_dates)


@index_eva_bp.get('/data')
def table():
    filters = []
    create_date = request.args.get('createDate', type=str)
    if create_date:
        filters.append(FundIndexEva.create_date == create_date)
    eva_type = request.args.get('evaType', type=str)
    if eva_type:
        filters.append(FundIndexEva.eva_type == eva_type)
    ttype = request.args.get('ttype', type=str)
    if ttype:
        filters.append(FundIndexEva.ttype == ttype)
    index_eva_list = FundIndexEva.query.filter(*filters).layui_paginate()
    return table_api(data=model_to_dicts(schema=FundIndexEvaSchema, data=index_eva_list.items), count=index_eva_list.total)























